﻿using UnityEngine;
using System.Collections;
using System;

/// <summary>
/// Script to maintain the score throughout the game.
/// </summary>
public class ScoreKeeper : MonoBehaviour {

	public int Score = 0;
	public int HighScore = 0;
	public MeshFilter HundredsDigit;
	public MeshFilter TensDigit;
	public MeshFilter OnesDigit;
	public MeshFilter [] NumberMeshes;
	public TextMesh HighScoreText;

	float deltaRotate = 0f;
	float deltaRotateStart = 1f;

	int lastHundreds = 0;
	int lastTens = 0;
	int lastOnes = 0;
	bool rotatingHundreds = false;
	bool rotatingTens = false;
	bool rotatingOnes = false;

	// Use this for initialization
	void Start () {
		this.LoadHighScore();
		this.HighScoreText.text = String.Format("{0:D3}",this.HighScore);
	}

	void LoadHighScore() {
		this.HighScore = PlayerPrefs.GetInt("HighScore",0);
	}

	public void SaveHighScore() {
		if (this.Score >= this.HighScore) {
			PlayerPrefs.SetInt("HighScore", this.HighScore);
		}
	}

	// Update is called once per frame
	void Update () {
		if (deltaRotate > 0f) {
			deltaRotate -= Time.deltaTime;
			if (rotatingOnes) {
				float y = Mathf.Lerp(0f,360f,deltaRotateStart - deltaRotate);
				Vector3 rot = OnesDigit.transform.localEulerAngles;
				rot.y = y;
				OnesDigit.transform.localEulerAngles = rot;
			}
			if (rotatingTens) {
				float y = Mathf.Lerp(0f,360f,deltaRotateStart - deltaRotate);
				Vector3 rot = TensDigit.transform.localEulerAngles;
				rot.y = y;
				TensDigit.transform.localEulerAngles = rot;
			}
			if (rotatingHundreds) {
				float y = Mathf.Lerp(0f,360f,deltaRotateStart - deltaRotate);
				Vector3 rot = HundredsDigit.transform.localEulerAngles;
				rot.y = y;
				HundredsDigit.transform.localEulerAngles = rot;
			}

		}
		else {
			rotatingOnes = false;
			rotatingTens = false;
			rotatingHundreds = false;
		}
	}

	public void IncrementScore()
	{
		this.Score++;
		if (this.Score > this.HighScore) {
			this.HighScore = this.Score;
			this.HighScoreText.text = String.Format("{0:D3}",this.HighScore);
		}

		// Let's just kill this?
		if (this.Score > 999) this.Score = 999;

		string numberString = string.Format("{0:D3}", this.Score);
		int hundreds = System.Int32.Parse(numberString[0].ToString());
		int tens = System.Int32.Parse(numberString[1].ToString());
		int ones = System.Int32.Parse(numberString[2].ToString());
		if (hundreds != lastHundreds) {
			lastHundreds = hundreds;
			deltaRotate = deltaRotateStart;
			rotatingHundreds = true;
		}
		if (tens != lastTens) {
			lastTens = tens;
			deltaRotate = deltaRotateStart;
			rotatingTens = true;
		}
		if (ones != lastOnes) {
			lastOnes = ones;
			deltaRotate = deltaRotateStart;
			rotatingOnes = true;
		}

		this.HundredsDigit.mesh = this.NumberMeshes[hundreds].mesh;
		this.TensDigit.mesh = this.NumberMeshes[tens].mesh;
		this.OnesDigit.mesh = this.NumberMeshes[ones].mesh;

	}
}
